package com.geekaca.news.controller.admin;

import com.geekaca.news.domain.NewsTag;
import com.geekaca.news.service.TagService;
import com.geekaca.news.utils.NewsConstants;
import com.geekaca.news.utils.PageResult;
import com.geekaca.news.utils.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class TagsController {
    @Autowired
    private TagService tagService;

    @RequestMapping("/tags")
    public String tags(HttpServletRequest request) {
        request.setAttribute("path", "tags");
        return "admin/tag";
    }

    @RequestMapping("/tags/list")
    @ResponseBody
    public Result tagList(@Param("page") Integer page, @Param("limit") Integer limit) {
        if (page == null) {
            page = 1;
        }
        if (limit == null) {
            limit = 10;
        }
        Integer totalTags = tagService.getTotalTags();
        List<NewsTag> tagList = tagService.getAllTags(page, limit);


        Result rs = new Result();
        rs.setResultCode(NewsConstants.RESULT_OK);
        PageResult pageResult = new PageResult(tagList, totalTags, limit, page);

        rs.setData(pageResult);
        return rs;
    }

    @PostMapping("tags/save")
    @ResponseBody
    public Result tagSave(@Param("tagName") String tagName) {
        Result result = new Result();
        int i = tagService.insertTag(tagName);
        if(i>0){
            result.setResultCode(NewsConstants.RESULT_OK);
            result.setMessage("添加标签成功");
        }else{
            result.setResultCode(NewsConstants.RESULT_FAIL);
            result.setMessage("添加标签失败");
        }
        return result;
    }

    @PostMapping("tags/delete")
    @ResponseBody
    public Result tagDel(@RequestBody List<Long> tagIds){
        Result res = new Result();
        tagIds.forEach(tagId->{
            int i = tagService.delTag(tagId);
            if(i>0){
                res.setResultCode(NewsConstants.RESULT_OK);
                res.setMessage("标签删除成功");
            }else{
                res.setResultCode(NewsConstants.RESULT_FAIL);
                res.setMessage("标签删除失败");
            }
        });
        return res;
    }

}
